/**
 * @file 预约时间
 * @author yangjiangming <449654337@qq.com>
 * @date 2018/12/14 16:38:57
 */

layui.define(['layer', 'dayjs', 'Vue', '$http', 'lodash', 'dayjs'], function(exports) {
    var $ = layui.$;
    var Vue = layui.Vue;
    var $http = layui.$http;
    var layer = layui.layer;
    var dayjs = layui.dayjs;
    var lodash = layui.lodash;

    // 获取排期
    var SCHEDULE_DATE_LIST_URL = '/schedule/date.action';
    var SCHEDULE_TIME_LIST_URL = '/schedule/back/time.action';
    var SCHEDULE_GET_STOCK_USED_ORDER_DETAIL_URL = '/schedule/getStockUsedOrderDetail.action';
    var CHECK_ORDER_DUTYTIME_EXCHANGE_URL = '/schedule/checkServTimeCanChang.action';
    // 获取自动派单时间
    var GET_AUTO_DISTRIBUTE_TIME = '/schedule/auto/distribute/time.action';

    var options;
    var currentDate;
    var autoTimeStart;
    var autoTimeEnd;

    /**
     * 获取日期的月份
     * @param date 日期
     * @returns {number} 月份
     * @private
     */
    function _getMonth(date) {
        return dayjs(date).month() + 1;
    }

    /**
     * 关闭预约时间选择窗口
     * @private
     */
    function _closeDialog() {
        var index = parent.layer.getFrameIndex(window.name);
        parent.layer.close(index);
    }

    function getDefaultTime(options) {
        $http.$get(GET_AUTO_DISTRIBUTE_TIME, {
            plat: options.plat,
            platWork: options.platWork,
            cityId: options.cityId,
            productId: options.productId,
            showProductId: options.showProductId,
            bizType: options.bizType
        }).then(function(data) {
            debugger
            let autoDistributeTime = data.split("-");
            autoTimeStart = parseInt(autoDistributeTime[0].replace(":", ""));
            autoTimeEnd = parseInt(autoDistributeTime[1].replace(":", ""));
        }, function(msg) {
            autoTimeStart = undefined;
            autoTimeEnd = undefined;
        });
    }

    /**
     * 判断当前时间是否在预约时间内
     * @param choiceTime
     * @returns {boolean}
     */
    function processTime(choiceTime) {
        let timeNum = parseInt(choiceTime.replace(":", ""));
        if (timeNum < autoTimeStart || timeNum >= autoTimeEnd) {
            return false;
        }
        return true;
    }

    /**
     * 初始化预约时间组件
     */
    function initDutyTimeComponent() {
        var vm = new Vue({
            el: '#dutytime-picker',
            template: '#dutyTime',
            filters: {
                date: function(date) {
                    return date.slice(5);
                }
            },
            data: function() {
                return {
                    date: '',
                    time: '',
                    month: '',
                    dateList: [],
                    timeList: [],
                    currentDate: '',
                    //defaultChooseData是走新逻辑数组
                    defaultChooseData: [],
                    //chooseData是当前订单对应的对象
                    chooseData: {},
                    // currentData是当前订单对应的对象 不清空
                    currentData: {},
                    //changeData是交换对象
                    changeData: {}
                };
            },
            computed: {
                defaultActiveDate: function() {
                    var date = this.dateList.find((date) => date.defaultActive)
                    return date;
                },
                currentDateList: function() {
                    const that = this;
                    let dateList = that.dateList.filter(function(item) {
                        return _getMonth(item.date) === that.month;
                    });

                    if (dateList.length) {
                        const firstDayOfWeek = dayjs(dateList[0].date).day();
                        const placeholderCount = firstDayOfWeek === 0 ?
                            6 :
                            firstDayOfWeek - 1;
                        const placeholderList = new Array(placeholderCount)
                            .fill({ date: '', disabled: true });
                        dateList = placeholderList.concat(dateList);
                    }

                    return dateList;
                },
                dateListGroup: function() {
                    return lodash.chunk(this.currentDateList, 7);
                },
                timeListGroup: function() {
                    return lodash.chunk(this.timeList, 7);
                },
                tabList: function() {
                    var tabList = [];
                    var tabListBuffer = {};

                    this.dateList.forEach((item) => {
                        var month = _getMonth(item.date);
                        if (!tabListBuffer[month]) {
                            tabListBuffer[month] = true;
                            tabList.push({
                                text: month + '月',
                                value: month
                            });
                        }
                    });

                    return tabList;
                },
            },
            mounted() {
                this.initPage();
            },
            methods: {
                initPage: function() {
                    var that = this;
                    that.initDateList().then(function(data) {
                        that.initCalendarStatus();
                    });
                    getDefaultTime(options);
                },
                initDateList: function() {
                    var that = this;
                    return that.fetchDateList().then(function(data) {
                        that.currentDate = data.nowTime;
                        that.dateList = data.dateList;
                        return data;
                    });
                },
                initTimeList: function(date) {
                    var that = this;
                    return that.fetchTimeList(date).then(function(data) {
                        that.timeList = that._timeDataAdapter(data);
                        that.defaultActiveIndex = data.defaultActiveIndex;
                        // 显示当前服务商库存已满
                        $('#spStock').hide();
                        if (data.spStockCanServ != null && data.spStockCanServ == 1) {
                            $('#spStock').show();
                        }
                        that.initNewTimeList(data)
                        return data;
                    });
                },
                initNewTimeList: function(res) {
                    var that = this;
                    this.chooseData = {}
                    try {
                        if (options.changeDutyData.date == this.date){
                            this.changeData = options.changeDutyData
                        }else {
                            this.changeData = {
                                date: this.date,
                                startIndex: 0,
                                endIndex: -1,
                                timeOut: 1,
                                workId: null,
                            }
                        }
                    }catch (error){
                        console.log(error)
                    }

                    that.defaultChooseData = res.usedOrderStockDetailVoList || []
                    that.defaultChooseData.forEach(item => {
                        if (item.workId == options.workId) {
                            this.chooseData = item
                            this.currentData = item
                        }
                    })

                },
                isChoose(index) {
                    var that = this;
                    var statu = false;
                    that.defaultChooseData.forEach(item => {
                        if (item.startIndex <= index && item.endIndex > index) {
                            statu = true
                            return;
                        }
                    })
                    return statu
                },
                initCalendarStatus: function() {
                    var that = this;
                    var dutyTime = options.dutyTime;
                    var defaultActiveDate = that.defaultActiveDate;

                    // 没有预约时间且存在默认号数
                    // 或存在预约时间，但预约时间已过期，且存在默认号数
                    if ((!dutyTime && defaultActiveDate) ||
                        (dutyTime && dayjs(dutyTime).isBefore(currentDate) && defaultActiveDate)
                    ) {
                        let date = defaultActiveDate.date;
                        that.date = date;
                        that.initTimeList(date).then(function(data) {
                            that.time = that.timeList[data.defaultActiveIndex].time;
                        });
                    } else if (dutyTime && !dayjs(dutyTime).isBefore(that.currentDate)) {
                        let dutyTimeDayjsObj = dayjs(dutyTime);
                        let date = dutyTimeDayjsObj.format('YYYY-MM-DD');
                        let time = dutyTimeDayjsObj.format('HH:mm');

                        that.date = date;
                        that.time = time;
                        that.initTimeList(date);
                    }

                    that.month = _getMonth(that.date);
                },
                handleDateClick: function(data) {
                    if (data.disabled) {
                        return;
                    }
                    this.time = '';
                    this.date = data.date;
                    this.initTimeList(data.date);
                },
                handleTimeClick: function(data) {
                    if (data.disabled) {
                        return;
                    }
                    this.time = data.time;
                },
                newHandleTimeClick: function(data, index) {
                    var isWhite = true
                    var that = this
                    that.changeData = {}
                    this.time = ''
                    //如果点击的是自己，不可以生效
                    if (this.date == this.currentData.date && this.currentData.startIndex <= index && this.currentData.endIndex > index) {
                        return;
                    }

                    //如果点击的是其他订单的蓝色块
                    var isSuccess = false;
                    var exchangeData;
                    this.defaultChooseData.forEach(item => {
                        if (item.startIndex <= index && item.endIndex > index) {
                            isWhite = false
                            if (item.endIndex - item.startIndex == this.currentData.endIndex - this.currentData.startIndex) {
                                if (that.currentData.timeOut == 1 && item.timeOut == 1) {
                                    isSuccess = true
                                    exchangeData = item
                                }
                            }

                        }
                    })

                    if(isSuccess){
                        $http.$get(CHECK_ORDER_DUTYTIME_EXCHANGE_URL, {
                            workId: options.workId,
                            exchangeWorkId: exchangeData.workId
                        }).then(function (data) {
                            if (data) {
                                isSuccess = true
                                that.changeData = exchangeData
                                that.time = that.timeList[exchangeData.startIndex].time
                            } else {
                                layer.msg('不满足交换条件');
                            }
                        });
                    }

                    if (!isWhite && !isSuccess) {
                        layer.msg('不满足交换条件');
                    }
                    //如果和白色块交换
                    if (data.disabled) {
                        return;
                    }
                    if (isWhite) {
                        this.time = data.time;
                        this.changeData = {
                            startIndex: index,
                            endIndex: index + 1,
                            workId: null,
                            date: this.date
                        }
                    }
                },
                getTitleWorkId(index) {
                    var titleWorkId = 0
                    this.defaultChooseData.forEach(item => {
                        if (item.startIndex <= index && item.endIndex > index) {
                            titleWorkId = item.workId
                        }
                    })
                    return titleWorkId == 0 ? false : '工单号：' + titleWorkId
                },
                handleMonthClick: function(data) {
                    this.time = '';
                    this.date = '';
                    this.month = data.value;
                },
                handleSubmit: function() {
                    var date = this.date;
                    var time = this.time;
                    var exchangeWorkId = this.changeData.workId;
                    var changeData = this.changeData;

                    if (!date || !time) {
                        layer.msg('请先选择日期和时间');
                        return;
                    }

                    var dutyTime = [date, time + ':00'];

                    if (typeof options.confirm === 'function') {
                        options.confirm(dutyTime.join(' '), changeData);
                    }

                    _closeDialog();
                },
                check: function(time) {
                    debugger
                    // 是否有自动派单时间
                    if (autoTimeStart && autoTimeEnd) {
                        let isTrue = processTime(time);
                        if (!isTrue) {
                            $("#tip").removeClass("layui-hide");
                        } else {
                            $("#tip").addClass("layui-hide");
                        }
                    }
                },
                handleCancel: function() {
                    _closeDialog();
                },
                fetchDateList: function(params) {
                    return $http.$get(SCHEDULE_DATE_LIST_URL, params);
                },
                fetchTimeList: function(date) {
                    return $http.$get(SCHEDULE_TIME_LIST_URL, {
                        scheDate: date,
                        plat: options.plat,
                        platWork: options.platWork,
                        channelId: options.channelId,
                        cityId: options.cityId,
                        productId: options.productId,
                        showProductId: options.showProductId,
                        workId: options.workId,
                        type: options.type,
                        productNum: options.productNum,
                        isGrid: options.isGrid,
                        latitude: options.latitude,
                        longitude: options.longitude,
                        servCategId: options.servCategId,
                        bizType: options.bizType,
                        isAvailableWeek: options.isAvailableWeek,
                    });
                },
                _timeDataAdapter: function(data) {
                    if (!data || (data && !data.times)) {
                        return [];
                    }
                    var timeArray = data.times.split('');

                    return timeArray.map((flag, index) => {
                        let houer = Math.floor(index / 4);
                        let minute = (index % 4) === 0 ? '00' : index % 4 * 15;

                        return {
                            time: (houer < 10 ? '0' + houer : houer) + ':' + minute,
                            disabled: flag !== '1'
                        };
                    });
                },
            }
        });
    }

    /**
     * 初始化页面
     */
    function initPage() {
        options = parent.window.dutyTimeOptions;
        initDutyTimeComponent();
    }

    function initEvent() {}

    function init() {
        initPage();

        initEvent();
    }

    init();

    exports("oms_order_dutytime");
});